package data

import (
    "encoding/json"
    "fcs-api/src/app/model"
    "fcs-api/src/app/utils"
    "fcs-api/src/app/utils/resource"
    "log"
    "net"
    "net/http"
    "time"

    "git.inspur.com/x/common/loggerfactory"
)

var logger = loggerfactory.GetLogger()
var K8sApiErr bool = false
var Eip_address = ""

func GetMetricValue(metricName string, metricTarget string, metricType string) string {
    /*
    	@param  metricName  string
    	@param  metricResourceId string
    	@param	metricType string
    	@return  value float64
    	TODO
    */
    //metricValue = metricData.GetMetricValue(metricName, metricTarget, metricType)
    //return metricValue
    //log.Printf("metricName: %s, metricTarget: %s, metricType: %s", metricName, metricTarget, metricType)
    if DataStoreErr {
        return "1"
    }
    if K8sApiErr {
        return "2"
    }
    r, err := http.NewRequest("GET", model.Base.FunctionInvokeHost, nil)
    if err != nil {
        logger.Error("GetMetricValue NewRequest error : ", err)
        return "3"
    }
    _, err = http.DefaultClient.Do(r)
    if err != nil {
        logger.Error("GetMetricValue Client.Do error : ", err)
        return "3"
    }
    return "0"
}

func GetVirtualMachineMetricValue() string {
    token := utils.GetAdminToken()
    if token != "" {
        ecsListUrl := "ecs/v1.1/servers/1/100?fast=true&searchField=name&searchValue=fcs-vpc-proxy"
        url := model.Base.EcsHost + ecsListUrl
        // 获取ecs列表中名为fcs-vpc-proxy的集群
        body, err := utils.HttpReq(url, "bearer "+token, "GET", nil, nil)
        if err != nil {
            logger.Error("GetVirtualMachineMetricValue: Query ecs server list error %s", err.Error())
            return "2"
        }
        ecsListResult := new(resource.EcsListResult)
        err = json.Unmarshal(body, ecsListResult)
        if err != nil {
            logger.Error("GetVirtualMachineMetricValue: Unmarshal ecs server list response body error %s, body is %s",
                err.Error(), string(body))
            return "3"
        }
        if ecsListResult.Data.TotalCount != 0 {
            for i := 0; i < ecsListResult.Data.TotalCount; i++ {
                if ecsListResult.Data.Servers[i].Status != "active" {
                    logger.Error("GetVirtualMachineMetricValue: ecs status err", err)
                    return "4"
                }
            }
        }
        return "0"
    } else {
        return "5"
    }
}

func GetEipMetricValue() string {
    token := utils.GetAdminToken()
    if token != "" {
        token = "bearer " + token
        clusterListUrl := "cks/cluster/v1/clusters/overview?size=6&index=1&name=fcs-cluster"
        url := model.Base.IceHost + clusterListUrl
        log.Print(url)
        log.Print(token)
        // 获取集群列表中名为fcs-cluster的集群
        body, err := utils.HttpReq(url, token, "GET", nil, nil)
        if err != nil {
            logger.Error("GetEipMetricValue: Query ice cluster list error %s", err.Error())
            return "1"
        }
        clusterList := new(resource.ClusterList)
        err = json.Unmarshal(body, clusterList)
        if err != nil {
            logger.Error("GetEipMetricValue: Unmarshal ice cluster list response body error %s, body is %s",
                err.Error(), string(body))
            return "2"
        }
        if clusterList.TotalCount == 1 {
            if clusterList.Result[0].Eip != "" {
                Eip_address = clusterList.Result[0].Eip
                clusterListUrl := "eip/v1.1/eips?eipAddress=" + clusterList.Result[0].Eip
                url := model.Base.IceHost + clusterListUrl
                // 获取集群列表中名为fcs-cluster的集群
                body, err := utils.HttpReq(url, token, "GET", nil, nil)
                if err != nil {
                    logger.Error("GetEipMetricValue: Query ice clusterListUrl error %s", err.Error())
                    return "1"
                }
                var e map[string]interface{}
                if err := json.Unmarshal(body, &e); err != nil {
                    logger.Error("GetEipMetricValue: Error parsing the response body: %s", err)
                    return "2"
                }
                if e["status"] != "ACTIVE" {
                    logger.Error("GetEipMetricValue: Error eip status: %s", e["status"])
                    return "3"
                }
            }
        }
        return "0"
    } else {
        return "4"
    }

}

func GetClusterMetricValue() string {
    if Eip_address != "" {
        ports := []string{"80"}
        gather := tcpGather(Eip_address, ports)
        if gather["80"] == "failed" {
            logger.Error("GetClusterMetricValue:Eip_address : %s is err", Eip_address)
            return "1"
        }
    }
    return "0"
}

func tcpGather(ip string, ports []string) map[string]string {
    results := make(map[string]string)
    for _, port := range ports {
        address := net.JoinHostPort(ip, port)
        // 3 秒超时
        conn, err := net.DialTimeout("tcp", address, 3*time.Second)
        if err != nil {
            results[port] = "failed"
            // todo log handler
        } else {
            if conn != nil {
                results[port] = "success"
                _ = conn.Close()
            } else {
                results[port] = "failed"
            }
        }
    }
    return results
}
